package com.controller;

import com.base.*;
import com.bean.WebsiteContent;
import com.bean.anno.LogAnno;
import com.github.pagehelper.PageHelper;
import com.mapper.mysql.WebsiteContentMapper;
import com.mapper.repository.mysql.WebsiteContentRepository;
import com.utils.HTMLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;

@RestController
@RequestMapping("website")
public class WebsiteContentController extends BaseController {

    @Autowired
    private WebsiteContentMapper websiteMapper;

    @Autowired
    private WebsiteContentRepository websiteRepository;

    @LogAnno(apiName = "获取网址")
    @PostMapping("list")
    public AjaxResult list(@RequestBody AjaxRequest<WebsiteContent> request){
        WebsiteContent website = request.getT();
        MetaInfo metaInfo = request.getMetaInfo();

        PageHelper.startPage(metaInfo.getPage(),metaInfo.getSize());
        List<WebsiteContent> list = websiteMapper.select(website);

        return success("查询成功",list,metaInfo);
    }

    @LogAnno(apiName = "获取网址")
    @GetMapping("{id}")
    public AjaxResult getOne(@PathVariable("id") String id){
        WebsiteContent websiteContent = websiteRepository.getById(id);
        System.out.println(websiteContent.toString());
        return success("查询成功",websiteContent);
    }

    @LogAnno(apiName = "添加网址")
    @PostMapping("add")
    public AjaxResult add(@RequestBody WebsiteContent website){
        int count = websiteRepository.countByLink(website.getLink());
        if(count>0){
            return error("新增的链接已存在");
        }
        String id = UUID.randomUUID().toString();
        website.setId(id);
        website.setCreatedate(LocalDate.now());
        websiteRepository.save(website);
        return success("新增成功");
    }

    @LogAnno(apiName = "删除网址")
    @PostMapping("del")
    public AjaxResult del(@RequestBody WebsiteContent website){
        websiteRepository.delete(website);
        return success("删除成功");
    }

    @LogAnno(apiName = "更新网址")
    @PostMapping("update")
    public AjaxResult update(@RequestBody WebsiteContent website){
        int count = websiteRepository.countByLinkAndIdIsNot(website.getLink(),website.getId());
        if(count>0){
            return  error("更新的链接已存在");
        }
        website.setUpdatedate(LocalDate.now());
        websiteRepository.save(website);
        return success("更新成功");
    }


    @Autowired
    private HTMLUtil htmlUtil;

    @PostMapping("/favicon")
    public ResponseEntity<Map<String, Object>> getFavicon(@RequestBody WebsiteContent request) {
        Map<String, Object> response = new HashMap<>();
        try {
            Map map = htmlUtil.getFaviconUrlsAndDescription(request.getLink());
            List<String> faviconUrls = (List<String>) map.get(Constants.Favicon);
            String description = (String) map.get(Constants.Description);
            //List<String> faviconUrls = htmlUtil.getFaviconUrls(request.getLink());

            response.put("success", true);
            response.put("message", faviconUrls.isEmpty() ? "未找到favicon图标" : "查询成功");
            response.put("data", faviconUrls.isEmpty() ? Arrays.asList("wlogo.png") : faviconUrls);
            response.put("data1", description);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Value("${website.img}")
    private String websiteImgFolder;

    @LogAnno(apiName = "上传图片")
    @PostMapping("uploadImg")
    public AjaxResult uploadImg(@RequestParam("file") MultipartFile file){
        System.out.println(file.getOriginalFilename());
        //System.out.println(file.getName());
        File folder = new File(websiteImgFolder);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        System.out.println(suffix);
        String img = UUID.randomUUID().toString();
        File imgFile = new File(websiteImgFolder,img+ suffix);
        try {
            file.transferTo(imgFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success("上传成功",img+suffix);
    }
}
